// var http = require('http');
var http = require('https');
var io = require('socket.io')();

const path = require('path')
const fs = require('fs')

var config = require('../config/config')

// 配置https服务
var server = http.createServer({
  cert: fs.readFileSync(path.join('./', 'cert', 'certificate.pem')),
  key: fs.readFileSync(path.join('./', "cert", "privatekey.pem"))
})

server.listen(config.socketPort, function () {
  console.log('socket:', config.socketPort, 'running...')
})

// 启动socket服务
var socket = io.listen(server, {
  origins: '*:*'
});

// 广播
function broadcastClientList() {
  io.of("/").clients((err, clients) => {
    if (!err) {
      console.log('SocketIOSupport:', clients);
      io.emit("listClients", clients);
    }
  });
}

// 用户id与socketID的映射关系
let socketMap = {};

// 监听客户端连接
socket.on('connection', function (socket) {
  broadcastClientList()

  // 实时维护map中id与socketID的映射关系
  socket.on('updSocketMap', data => {
    console.log('updSocketMap',data);
    socketMap[data.sender] = socket.id
    console.log('id与socketID的映射关系:',socketMap);
    io.emit('getSocketMap', socketMap)
  })

  // 监听客户端断开
  socket.on('disconnect', () => {
    console.log('客户端断开')
  })

  /**
   * 私信
   */
  socket.on('sendPrivateMsg', data => {
    let receiver = data.receiver;
    console.log(socketMap);
    console.log('用户发送了信息', data,socketMap[data.receiver])
    // 原来的写法：发送给所有用户(不合适).
    // io.sockets.emit("getPrivateMsg", data);
    if (receiver) {
      io.to(socketMap[data.receiver]).emit('getPrivateMsg', data)
    }
  })

  /**
   * 视频通话
   */
  socket.on('receiveConnect', data => {
    let receiver = data.receiver;
    if (receiver) {
      io.to(socketMap[data.sender]).emit('receiveConnect', {
        sender: socketMap[data.sender],
        receiver: socketMap[data.receiver]
      })
    }
  })

  socket.on('offerIce', data => {
    let receiver = data.receiver;
    if (receiver) {
      io.to(receiver).emit('offerIce', data)
    }
  })

  socket.on('offer', data => {
    let receiver = data.receiver;
    if (receiver) {
      io.to(receiver).emit('offer', data)
    }
  })

  socket.on('answer', data => {
    let receiver = data.receiver;
    if (receiver) {
      io.to(receiver).emit('answer', data)
    }
  })

  socket.on('answerIce', data => {
    let receiver = data.receiver;
    if (receiver) {
      io.to(receiver).emit('answerIce', data)
    }
  })

  // 直播
  socket.on('living', data => {
    io.of("/").clients((err, clients) => {
      if (!err) {
        io.emit("indexLiving", data);
      }
    });
  })

  // 直播间用户加入消息
  socket.on("joinRoom", data => {
    socket.join(data.name);

    io.to('myRoom').emit("someBodyJoinedIn", {
      studentSid: socket.id,
      username: data.username
    });
  });

  // 直播间消息
  socket.on("sendRoomMsg", data => {
    io.to('myRoom').emit("transmitRoomMsg",data);
  });

});